import { createStore } from 'vuex'
import { updateCartNumber } from '@/api/cart.js'

const USER_TOKEN_KEY = 'logou-shop-mobile-user-token'

export default createStore({
  state: {
    userToken: localStorage.getItem(USER_TOKEN_KEY),
    // 用于存储购物车的数据（sku 的 id，checked，count，image, title，price，stock，productId）
    cartList: [],
  },
  mutations: {
    setUserToken(state, userToken) {
      state.userToken = userToken
      localStorage.setItem(USER_TOKEN_KEY, userToken)
    },
    setCartList(state, cartList) {
      state.cartList = cartList
    },
    clearCartList(state) {
      state.cartList = []
    },
    addCart(state, item) {
      state.cartList.push(item)
    },
    cartCheckedChange(state, { id, checked }) {
      state.cartList.find(item => item.id === id).checked = checked
    },
    cartCountChange(state, { id, count }) {
      state.cartList.find(item => item.id === id).cart_num = count
    },
    cartAllCheckedChange(state, { checked }) {
      state.cartList.forEach(item => item.checked = checked)
    }
  },
  actions: {
    async cartCountChange(store, { id, count }) {
      store.commit('cartCountChange', { id, count })
      await updateCartNumber(id, count)
    },
  },
})
